/*
 * @Author: 'zhangkeqq' '2211709169@qq.com'
 * @Date: 2025-06-21 20:03:02
 * @LastEditors: your name
 * @LastEditTime: 2025-07-05 14:48:14
 * @FilePath: \vue3-admin\src\store\modules\user.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import {defineStore} from 'pinia'
import router from '@/router'
import { reqLogin,reqUserInfo,reqLogOut } from '@/api/user'
import type { LoginFormData,LoginResponseData } from '@/api/user/type'
import type {UserState} from './types/types'
import { SET_TOKEN, GET_TOKEN,REMOVE_TOKEN } from '@/utils/token'
// 引入路由
import {constantRoute,asyncRoute,anyRoute} from '@/router/routes'

// 引入深拷贝方法
//@ts-expect-error 没有ts类型
import cloneDeep from 'lodash/cloneDeep'

//用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(asyncRoute: any, routes: any) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}
const useUserStore = defineStore('User',{
    state:():UserState=>{ 
        return{
            token:GET_TOKEN(),
            menuRoutes:constantRoute,
            username:'',
            avatar:'',
            // 存储当前用户是否包含某一个按钮
            buttons:[],
        }
    },
    // 异步/逻辑
    actions:{
        //用户登录方法
        async userLogin(data:LoginFormData){
            const res:LoginResponseData = await reqLogin(data)
            if(res.code == 200){
                SET_TOKEN(res.data.token as string)
                localStorage.setItem('TOKEN',res.data.token as string)
            }else{
                return Promise.reject(res.data)
            }
        },
        //获取用户信息
        async userInfo(){
            const res = await reqUserInfo()
            if(res.code == 200){
                this.username = res.data.checkUser.username
                this.avatar = res.data.checkUser.avatar
                this.buttons = res.data.checkUser.buttons
                // 计算当前用户需要展示的异步路由
                console.log('res.data.checkUser.routes',res.data.checkUser.routes)
                const userAsyncRoute = filterAsyncRoute(cloneDeep(asyncRoute),res.data.checkUser.routes)
                console.log('asyncRoute',asyncRoute,'---')
                //菜单需要的数据
                this.menuRoutes = [...constantRoute,...userAsyncRoute,...anyRoute]
                // console.log(' this.menuRoutes', this.menuRoutes)
                // 目前路由器管理只有常量路由，计算完毕后异步路由和任意路由需要动态添加
                const newRoutes = [...userAsyncRoute,...anyRoute]
                newRoutes.forEach((route:any)=>{
                    router.addRoute(route)
                })
                return 'ok'
            }else{
                return Promise.reject(res.data)
            }
        },
        //用户退出登录方法
        async userLogout(){
            // 调用退出登录接口
           const res =   await reqLogOut()
           if(res.code == 200){
                // 清除数据
                this.token = ''
                this.username = ''
                this.avatar = ''
                REMOVE_TOKEN()
                 return 'ok'
           }else{
                return Promise.reject(res.message)
           }

        }
    }
})
export default useUserStore